package com.example.healthapp;


import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.example.healthapp.ble.OnBleConnectListener;
import com.example.healthapp.ble.OnDeviceSearchListener;
import com.example.healthapp.bluetoothlibrary.DeviceModule;
import com.example.healthapp.bluetoothlibrary.HoldBluetooth;
import com.example.healthapp.permission.PermissionListener;
import com.example.healthapp.permission.PermissionRequest;
import com.example.healthapp.utils.Analysis;

import java.util.ArrayList;
import java.util.List;

/**
 * BLE开发
 */
@RequiresApi(api = Build.VERSION_CODES.S)
public class NewBlewMainActivity extends AppCompatActivity implements View.OnClickListener {


    private final String[] requestPermissionArray = new String[]{
            Manifest.permission.BLUETOOTH_SCAN,
            Manifest.permission.BLUETOOTH_CONNECT,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
    };


    private Button btSearch, btConnect, btDisconnect, btSend;
    private TextView tvCurConState, tvName, tvAddress, tvSendResult, tvReceive,receiveData;
    private EditText etSendMsg;
    private RecyclerView lvDevices;
    //    private LinearLayout llDeviceList, llDataSendReceive;
    private final String TAG = "NewBlewMainActivity1";
    private Context mContext;


    private final List<DeviceModule> mModuleArray = new ArrayList<>();
    private final List<DeviceModule> mFilterModuleArray = new ArrayList<>();
    private HoldBluetooth mHoldBluetooth;
    private MyRecycleViewAdapter myRecycleViewAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_ble);

        mContext = NewBlewMainActivity.this;

        // 初始化视图
        initView();
        // 初始化监听器
        initListeners();
        // 初始化数据
        initData();
        // 初始化权限
        initPermissions();

        //初始化单例模式中的蓝牙扫描回调
        initHoldBluetooth();
    }

    private void initView() {
        btSearch = findViewById(R.id.bt_search);
        tvCurConState = findViewById(R.id.tv_cur_con_state);
        btConnect = findViewById(R.id.bt_connect);
        btDisconnect = findViewById(R.id.bt_disconnect);
        tvName = findViewById(R.id.tv_name);
        tvAddress = findViewById(R.id.tv_address);
        etSendMsg = findViewById(R.id.et_send_msg);
        btSend = findViewById(R.id.bt_to_send);
        tvSendResult = findViewById(R.id.tv_send_result);
        tvReceive = findViewById(R.id.tv_receive_result);
//        llDeviceList = findViewById(R.id.ll_device_list);
//        llDataSendReceive = findViewById(R.id.ll_data_send_receive);
        lvDevices = findViewById(R.id.lv_devices);
        //  receiveData = findViewById(R.id.tv_receive_results);
    }

    private void initListeners() {
        btSearch.setOnClickListener(this);
        btConnect.setOnClickListener(this);
        btDisconnect.setOnClickListener(this);
        btSend.setOnClickListener(this);


    }

    private void initData() {
        myRecycleViewAdapter = new MyRecycleViewAdapter(R.layout.layout_lv_devices_item, mFilterModuleArray);
        lvDevices.setLayoutManager(new LinearLayoutManager(this));
        lvDevices.setAdapter(myRecycleViewAdapter);

        myRecycleViewAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                DeviceModule deviceModule = mFilterModuleArray.get(position);
                tvName.setText(deviceModule.getName());
                tvAddress.setText(deviceModule.getMac());


            }
        });

    }

    private void initPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            PermissionRequest permissionRequest = new PermissionRequest();
            permissionRequest.requestRuntimePermission(NewBlewMainActivity.this, requestPermissionArray, new PermissionListener() {
                @Override
                public void onGranted() {
                    Log.d(TAG, "所有权限已授予");
                }

                @Override
                public void onDenied(List<String> deniedPermissions) {
                    for (String deniedPermission : deniedPermissions) {
                        Log.e(TAG, "被拒绝权限：" + deniedPermission);
                    }
                }
            });
        }
    }

    private void initHoldBluetooth() {
        mHoldBluetooth = HoldBluetooth.getInstance();
        final HoldBluetooth.UpdateList updateList = new HoldBluetooth.UpdateList() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void update(boolean isStart, DeviceModule deviceModule) {

                if (isStart && deviceModule == null){//更新距离值
                    myRecycleViewAdapter.notifyDataSetChanged();
                    return;
                }

                if (isStart){
                    mModuleArray.add(deviceModule);
                    addFilterList(deviceModule,true);
                }else {
//                    mTitle.updateLoadingState(false);
                }
            }

            @Override
            public void updateMessyCode(boolean isStart, DeviceModule deviceModule) {
                for (int i = 0; i < mModuleArray.size(); i++) {
                    if (mModuleArray.get(i).getMac().equals(deviceModule.getMac())) {
                        mModuleArray.remove(mModuleArray.get(i));
                        mModuleArray.add(i, deviceModule);
                        upDateList();
                        break;
                    }
                }
            }
        };
        mHoldBluetooth.initHoldBluetooth(NewBlewMainActivity.this, updateList);



        HoldBluetooth.OnReadDataListener dataListener = new HoldBluetooth.OnReadDataListener() {
            @Override
            public void readData(String mac, byte[] data) {

                String byteToString = Analysis.getByteToString(data, "GBK", true);
                Log.i(TAG, "readData: "+byteToString);
//                String dataSource = Analysis.hexStringToString(byteToString);
                tvReceive.setText(byteToString);
                final String finalString = byteToString + "\n"; // 将需要显示的字符串作为final变量
                //tvReceive.append(byteToString + "\n");
            }

            @Override
            public void reading(boolean isStart) {
            }

            @Override
            public void connectSucceed() {
                String name = mHoldBluetooth.getConnectedArray().get(0).getName();
                Log.i(TAG, "连接成功: "+name);
                Toast.makeText(mContext, "连接成功: "+name, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void errorDisconnect(final DeviceModule deviceModule) {//蓝牙异常断开
                Toast.makeText(mContext, "连接"+deviceModule.getName()+"失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void readNumber(int number) {
            }

            @Override
            public void readLog(String className, String data, String lv) {
                //拿到日志
            }

            @Override
            public void readVelocity(int velocity) {
            }
        };
        mHoldBluetooth.setOnReadListener(dataListener);

    }

    //更新列表
    @SuppressLint("NotifyDataSetChanged")
    private void upDateList() {
        mFilterModuleArray.clear();
        for (DeviceModule deviceModule : mModuleArray) {
            addFilterList(deviceModule,false);
        }
        myRecycleViewAdapter.notifyDataSetChanged();
    }

    //根据条件过滤列表，并选择是否更新列表
    @SuppressLint("NotifyDataSetChanged")
    private void addFilterList(DeviceModule deviceModule, boolean isRefresh){
        if (deviceModule.getName().equals("N/A")){
            return;
        }

//        if (!deviceModule.isBLE()){
//            return;
//        }

        deviceModule.isCollectName(this);
        mFilterModuleArray.add(deviceModule);
        if (isRefresh)
            myRecycleViewAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //退出这个界面，或是返回桌面时，停止扫描
        mHoldBluetooth.stopScan();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @SuppressLint("NotifyDataSetChanged")
    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.bt_search) {
//            llDataSendReceive.setVisibility(View.GONE);
//            llDeviceList.setVisibility(View.VISIBLE);
            mFilterModuleArray.clear();
            myRecycleViewAdapter.notifyDataSetChanged();
            mHoldBluetooth.scan(true);
        } else if (view.getId() == R.id.bt_connect) {

            String addressMac = tvAddress.getText().toString();
            if (TextUtils.isEmpty(addressMac)){
                Toast.makeText(mContext, "请选择设备！", Toast.LENGTH_SHORT).show();
                return;
            }

            for (int i = 0; i < mFilterModuleArray.size(); i++) {
                if (addressMac.equals(mFilterModuleArray.get(i).getMac())){
                    DeviceModule deviceModule = mFilterModuleArray.get(i);
                    if (deviceModule!=null){
                        mHoldBluetooth.connect(mFilterModuleArray.get(i));
                    }
                }
            }


        } else if (view.getId() == R.id.bt_disconnect) {
            String addressMac = tvAddress.getText().toString();
            if (TextUtils.isEmpty(addressMac)){
                Toast.makeText(mContext, "请选择设备！", Toast.LENGTH_SHORT).show();
                return;
            }

            for (int i = 0; i < mFilterModuleArray.size(); i++) {
                if (addressMac.equals(mFilterModuleArray.get(i).getMac())){
                    mHoldBluetooth.disconnect(mFilterModuleArray.get(i));
                }
            }


        } else if (view.getId() == R.id.bt_to_send) {
            String addressMac = tvAddress.getText().toString();
            if (TextUtils.isEmpty(addressMac)){
                Toast.makeText(mContext, "请选择设备！", Toast.LENGTH_SHORT).show();
                return;
            }
            if (TextUtils.isEmpty(etSendMsg.getText().toString())){
                Toast.makeText(mContext, "请输入数据！", Toast.LENGTH_SHORT).show();
                return;
            }
            if (Analysis.containsChinese(etSendMsg.getText().toString())){
                Toast.makeText(mContext, "请输入正确字符！", Toast.LENGTH_SHORT).show();
                return;
            }

            for (int i = 0; i < mFilterModuleArray.size(); i++) {
                if (addressMac.equals(mFilterModuleArray.get(i).getMac())){
                    byte[] bytes = Analysis.getBytes(etSendMsg.getText().toString().replaceAll(" ", ""), "GBK", true);
                    mHoldBluetooth.sendData(mFilterModuleArray.get(i),bytes);
                }
            }

        }
    }


    static class MyRecycleViewAdapter extends BaseQuickAdapter<DeviceModule, BaseViewHolder> {

        public MyRecycleViewAdapter(int layoutResId, @Nullable List<DeviceModule> data) {
            super(layoutResId, data);
        }

        @SuppressLint({"SetTextI18n", "UseCompatLoadingForDrawables"})
        @Override
        protected void convert(BaseViewHolder helper, DeviceModule twoListBean) {

            TextView tvDeviceName = (TextView) helper.getView(R.id.tv_device_name);
            TextView tvDeviceAddress = (TextView) helper.getView(R.id.tv_device_address);
            TextView tvDeviceRSSI = (TextView) helper.getView(R.id.tv_device_rssi);

            String deviceName = twoListBean.getName();
            String deviceAddress = twoListBean.getDevice().getAddress();
            int rssi = twoListBean.getRssi();

            tvDeviceName.setText(TextUtils.isEmpty(deviceName) ? "NULL" : deviceName);
            tvDeviceAddress.setText(deviceAddress);
            tvDeviceRSSI.setText("RSSI：" + rssi);

        }
    }


}

